package com.ruoyi.market.http;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.market.http.model.ApiResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AdminHttpUtil {

    @Value("${api.hostUrl}")
    private String hostUrl;

    @Value("${api.appId}")
    private String appId;

    public ApiResponse httpReq(String uri, JSONObject object) {
        try {

            String url = hostUrl + uri;
            String tranData = JSONObject.toJSONString(object);

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("appId", appId);
            paramMap.put("version", "1.0.1");
            paramMap.put("tranData", tranData);

            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("mobileSerialNo", "1234567890");
            headerMap.put("mobileType", "IOS");
            headerMap.put("channelCode", "default");
            headerMap.put("clientType", "h5");
            headerMap.put("timestamp", String.valueOf(System.currentTimeMillis()));

            HttpRequest httpRequest = HttpUtil.createPost(url);
            httpRequest.headerMap(headerMap, true);
            httpRequest.form(paramMap);

            String body = httpRequest.execute().body();
            System.out.println("【body】"+ body);

            JSONObject jsonObject = JSON.parseObject(body);
            String respCode = jsonObject.getString("rspCode");
            String respMsg = jsonObject.getString("rspMsg");
            if (StrUtil.equals("0001", respCode)){
                JSONObject data = jsonObject.getJSONObject("data");
                return ApiResponse.success(data);
            }
            return ApiResponse.error(respCode, respMsg);
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return ApiResponse.error();
    }

}
